package com.example.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.AjaxResult;
import com.example.common.utils.DateUtils;
import com.example.food.domain.Goods;
import com.example.order.domain.Order;
import com.example.order.mapper.OrderMapper;
import com.example.order.service.OrderService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * OrderService实现层
 * @author jiangshoutong
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {


    @Autowired
    private OrderMapper orderMapper;

    /**
     * 订单列表
     * @param o
     * @return
     */
    @Override
    public AjaxResult selectList(Order o) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Objects.nonNull(o.getOrderNumber()),Order::getOrderNumber,o.getOrderNumber());
        orderMapper.selectList(wrapper);
        return AjaxResult.success().put("data", orderMapper.selectList(wrapper));
    }

    /**
     * 下单
     * @param o
     * @return
     */
    @Override
    public AjaxResult addOther(Order o) {
        o.setOrderNumber(getNumberCode("O"));
        o.setStatus(0);
        orderMapper.insert(o);
        return AjaxResult.success("下单成功");
    }

    /**
     * 统计方法
     * @param o
     * @return
     */
    @Override
    public AjaxResult statistics(Order o) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        List<Order> records = orderMapper.selectList(wrapper);

        List<String> goodsNames = records.stream().map(f -> f.getGoodsName()).collect(Collectors.toList());
        QueryWrapper<Order> wrapper1 = new QueryWrapper<>();
        wrapper.select("goodsName,count(0) as count,sum(price) as amount")
                .in("goodsName",goodsNames)
                .groupBy("goodsName");
        List<Map<String,Object>> list = orderMapper.selectMaps(wrapper);
        return AjaxResult.success().put("data",list);
    }

    public String getNumberCode(String prefix) {
        StringBuilder builder = new StringBuilder();
        builder.append(prefix);
        String incKey = DateUtils.dateTime();
        String randomNumeric = RandomStringUtils.randomNumeric(3);
        builder.append(incKey).append(randomNumeric);
        return builder.toString();

    }
}
